package com.doghome.testsecurity.service;

import com.doghome.testsecurity.dao.UserMapper;
import com.doghome.testsecurity.pojo.Role;
import com.doghome.testsecurity.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;


@Service("userDetailServiceImpl")
public class UserDetailServiceImpl implements UserDetailsService {

    private final static Logger logger = LoggerFactory.getLogger(UserDetailServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    @Autowired
    @Qualifier("myEncoder")
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapper.selectByName(s);
        if(user == null){
            throw new UsernameNotFoundException("用户不存在");
        }
        String pwd = passwordEncoder.encode(user.getPassword());
        logger.info(pwd);
        Set<Role> roles = user.getRoles();
        Set<GrantedAuthority> set = new HashSet<>();
        for(Role role : roles){
            GrantedAuthority ga = new SimpleGrantedAuthority(role.getRoleName());
            set.add(ga);
        }

        return new org.springframework.security.core.userdetails.User(user.getUsername(),pwd,set);
    }
}
